package com.greatwall.hip.cms.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.greatwall.hip.cms.model.Result;
import com.greatwall.hip.cms.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author TianLei
 * @version V1.0
 */
public class JWTFilter extends AccessControlFilter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        if(logger.isDebugEnabled()) {
//            logger.debug("访问的URI: {}", ((HttpServletRequest) request).getRequestURI());
//        }
//        String webToken = JWTTokenUtil.resolveToken((HttpServletRequest) request);
//        String loginName = StringUtils.EMPTY;
//        if (StringUtils.isBlank(webToken)) {
//            webToken = "";
//        } else {
//            // 解码 jwt
//            try {
//                DecodedJWT decodeJwt = JWT.decode(webToken);
//                loginName = decodeJwt.getClaim("loginName").asString();
//            } catch (JWTDecodeException decodeException) {
//                WebUtil.sendResponse(response, Result.fail("TOKEN解析异常，请检查格式是否错"));
//                return false;
//            }
//        }
//
//        JWTToken token = new JWTToken(loginName, webToken);
//        try {
//            // 交给自定义realm进行jwt验证和对应角色,权限的查询
//            getSubject(request, response).login(token);
//        } catch (AuthenticationException e) {
//            // 转发给指定的 controller, 进行统一异常处理
//            WebUtil.sendResponse(response, Result.fail("权限不足"));
//            return false;
//        }
        return true;
    }
}
